package com.one.group.admin.dao.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.one.group.admin.dao.AdvertDao;
import com.one.group.enums.ErrorCode;
import com.one.group.model.dto.AdvertQueryDto;
import com.one.group.model.entity.Advert;
import com.one.group.model.vo.AdvertListVo;
import com.one.group.utils.ThrowUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.BulkOperations;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * @Author wanbo
 * @Date 2025/9/29 13:54
 */
@Slf4j
@Repository
public class AdvertDaoImpl implements AdvertDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public Advert findAdvertById(String id) {
        Advert advert = mongoTemplate.findById(id, Advert.class);
        return advert;
    }

    @Override
    public AdvertListVo findAdvertByQueryDto(AdvertQueryDto advertQueryDto) {
        //1. 构建查询条件
         Query query = new Query();
        // TODO 从当前线程获取用户判断是否是管理员，是总管理员就不管了
        String adminId = (String) StpUtil.getLoginId();
        if (!adminId.equals("1")) {
            query.addCriteria(Criteria.where("tenantId").is(String.valueOf(StpUtil.getExtra("tenant_id"))));
        }
        // 添加查询条件
        // 根据广告名称进行模糊查询
        if (advertQueryDto.getName() != null && !"".equals(advertQueryDto.getName())){
            Pattern pattern = Pattern.compile("^.*" + advertQueryDto.getName() + ".*$", Pattern.CASE_INSENSITIVE);
            query.addCriteria(Criteria.where("name").regex(pattern));
        }
        // 根据小区id进行查询
        if (advertQueryDto.getCellId() != null ){
            query.addCriteria(Criteria.where("cellId").is(String.valueOf(advertQueryDto.getCellId())));
        }
        // 根据状态进行查询
        if (advertQueryDto.getStatus() != null){
            query.addCriteria(Criteria.where("status").is(advertQueryDto.getStatus()));
        }

        //4. 查询总记录数
        long count = mongoTemplate.count(query,  Advert.class);

        //5. 分页查询
        query.skip((advertQueryDto.getPage()-1)*advertQueryDto.getLimit()).limit(advertQueryDto.getLimit());

        List<Advert> advertList = mongoTemplate.find(query, Advert.class);

        AdvertListVo advertListVo = new AdvertListVo();
        advertListVo.setAdvertList(advertList);
        advertListVo.setCount(count);
        return advertListVo;
    }

    @Override
    public void inertAdvert(Advert advert) {
        mongoTemplate.save(advert);
    }

    @Override
    public void updateAdvert(Advert advert) {
        //1.创建修改的条件
        Query query=new Query();
        query.addCriteria(Criteria.where("_id").is(advert.getId()));

        //2.设置修改的字段
        Update update=new Update();
        update.set("name",advert.getName())
                .set("status",advert.getStatus())
                .set("chargeId",advert.getChargeId())
                .set("cellId",advert.getCellId())
                .set("position",advert.getPosition())
                .set("size",advert.getSize())
                .set("price",advert.getPrice())
                .set("image",advert.getImage())
                .set("tenantId",advert.getTenantId())
                .set("createTime",advert.getCreateTime())
                .set("updateTime",advert.getUpdateTime());

        //3.修改
        mongoTemplate.updateFirst(query,update,Advert.class);
    }

    @Override
    public void deleteAdvertById(String id) {
        Query query = new Query(Criteria.where("_id").is(id));
        mongoTemplate.remove(query,Advert.class);
    }

    @Override
    public void insertAdvertList(List<Advert> advertList) {
        BulkOperations bulkOps = mongoTemplate.bulkOps(BulkOperations.BulkMode.UNORDERED, Advert.class);
        bulkOps.insert(advertList);
        bulkOps.execute();
    }

    @Override
    public void deleteBatch(List<String> ids) {
        Query query = Query.query(Criteria.where("_id").in(ids));
        //
        if (StpUtil.getLoginId().equals("1")) {
            mongoTemplate.remove(query, Advert.class);
        }
        // TODO 如果是管理员的话就需要加这个，普通用户没有删除权限
//        query.addCriteria(Criteria.where("tenantId").is(String.valueOf(StpUtil.getExtra("tenant_id"))));

    }

    @Override
    public BigDecimal getTotalPrice() {

        Query query = new Query();
        query.addCriteria(Criteria.where("status").is(1));
        query.addCriteria(Criteria.where("tenantId").is(String.valueOf(StpUtil.getExtra("tenant_id"))));
        List<Advert> advertList = mongoTemplate.find(query, Advert.class);
        return advertList.stream().map(Advert::getPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    @Override
    public AdvertListVo findAdvertListByCellId(String cellId) {
        Query query = new Query();
//        String adminId = (String) StpUtil.getLoginId();
//        if (!adminId.equals("1")) {
//            query.addCriteria(Criteria.where("tenantId").is(String.valueOf(StpUtil.getExtra("tenant_id"))));
//        }
        query.addCriteria(Criteria.where("cellId").is(cellId));
        //4. 查询总记录数
        long count = mongoTemplate.count(query,  Advert.class);

        List<Advert> advertList = mongoTemplate.find(query, Advert.class);

        AdvertListVo advertListVo = new AdvertListVo();
        advertListVo.setAdvertList(advertList);
        advertListVo.setCount(count);
        return advertListVo;
    }
}
